<?php
namespace app\admin\controller;

use app\common\lib\CryptoJsAes;

class Crypto extends Common
{
    /**
     * 加密解密页
     * @author 贺强
     * @time   2023/7/27 15:39
     * @return \think\response\View
     */
    public function index()
    {
        $salt = env('app.aes_salt', '258369471xcvn019');
        $iv = env('app.aes_iv', 'y9shd1pdrwvapq8b');
        $pwd = env('app.aes_pwd', '9fd8bd921151');
        return view('', compact('salt', 'iv', 'pwd'));
    }

    /**
     * aes 256 加密
     * @author 贺强
     * @time   2023/5/16 15:45
     * @return string|\think\response\Json
     */
    public function encrypt()
    {
        if (!empty($this->admin['code'])) {
            return $this->admin;
        }
        $str = $this->request->post('str', '');
        if (empty($str)) {
            return ajax('要加密的字符串不能为空', 101);
        }
        $pwd = env('app.aes_pwd', '9fd8bd921151');
        $res = CryptoJsAes::encrypt($str, $pwd);
        return ajax('加密成功', 200, json_encode($res));
    }

    /**
     * aes 256 解密
     * @author 贺强
     * @time   2023/5/16 15:48
     * @return string|\think\response\Json
     */
    public function decrypt()
    {
        if (!empty($this->admin['code'])) {
            return $this->admin;
        }
        $str = $this->request->post('str', '');
        if (empty($str)) {
            return ajax('要解密的字符串不能为空', 101);
        }
        if (!is_json($str)) {
            return ajax('输入的字符串格式错误', 201);
        }
        $pwd = env('app.aes_pwd', '9fd8bd921151');
        $res = CryptoJsAes::decrypt($str, $pwd);
        if (!$res) {
            return ajax('解密失败', 400);
        }
        return ajax('解密成功', 200, $res);
    }

    /**
     * aes 128 加密
     * @author 贺强
     * @time   2023/5/16 15:45
     * @return string|\think\response\Json
     */
    public function encrypt2()
    {
        if (!empty($this->admin['code'])) {
            return $this->admin;
        }
        $str = $this->request->post('str', '');
        if (empty($str)) {
            return ajax('要加密的字符串不能为空', 101);
        }
        $passphrase = env('app.aes_salt', '258369471xcvn019');
        $iv = env('app.aes_iv', 'y9shd1pdrwvapq8b');
        $res = CryptoJsAes::encryptT($str, $passphrase, $iv);
        return ajax('加密成功', 200, $res);
    }

    /**
     * aes 128 解密
     * @author 贺强
     * @time   2023/5/16 15:48
     * @return string|\think\response\Json
     */
    public function decrypt2()
    {
        if (!empty($this->admin['code'])) {
            return $this->admin;
        }
        $str = $this->request->post('str', '');
        if (empty($str)) {
            return ajax('要解密的字符串不能为空', 101);
        }
        $passphrase = env('app.aes_salt', '258369471xcvn019');
        $iv = env('app.aes_iv', 'y9shd1pdrwvapq8b');
        $res = CryptoJsAes::decryptT($str, $passphrase, $iv);
        if (empty($res)) {
            return ajax('解密失败', 400);
        }
        return ajax('解密成功', 200, $res);
    }
}
